<template>
  <div class="coding-container">
    <!-- 顶部横幅 -->
    <div class="coding-header">
      <div class="header-content">
        <div class="header-left">
          <h1>编程实战</h1>
          <p>在线编程，实时评测，提升编程技能</p>
          <div class="quick-stats">
            <div class="stat-item">
              <span class="number">{{ userStats.solvedProblems }}</span>
              <span class="label">已解决</span>
            </div>
            <div class="stat-item">
              <span class="number">{{ userStats.totalSubmissions }}</span>
              <span class="label">提交次数</span>
            </div>
            <div class="stat-item">
              <span class="number">{{ userStats.acceptanceRate }}%</span>
              <span class="label">通过率</span>
            </div>
          </div>
        </div>
        
        <div class="header-right">
          <div class="coding-illustration">
            <el-icon class="code-icon"><Monitor /></el-icon>
            <div class="code-lines">
              <div class="code-line"></div>
              <div class="code-line short"></div>
              <div class="code-line"></div>
              <div class="code-line medium"></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索区域 -->
    <div class="filter-section">
      <div class="filter-content">
        <div class="search-bar">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索题目标题、标签..."
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="filter-controls">
          <el-select v-model="difficultyFilter" placeholder="难度" clearable>
            <el-option label="简单" value="easy" />
            <el-option label="中等" value="medium" />
            <el-option label="困难" value="hard" />
          </el-select>
          
          <el-select v-model="categoryFilter" placeholder="分类" clearable>
            <el-option 
              v-for="category in categories" 
              :key="category.value"
              :label="category.label" 
              :value="category.value" 
            />
          </el-select>
          
          <el-select v-model="statusFilter" placeholder="状态" clearable>
            <el-option label="未开始" value="not_attempted" />
            <el-option label="已解决" value="solved" />
            <el-option label="尝试过" value="attempted" />
          </el-select>
          
          <el-select v-model="sortBy" placeholder="排序">
            <el-option label="默认排序" value="default" />
            <el-option label="难度升序" value="difficulty_asc" />
            <el-option label="难度降序" value="difficulty_desc" />
            <el-option label="通过率" value="acceptance_rate" />
            <el-option label="最新发布" value="latest" />
          </el-select>
        </div>
      </div>
    </div>

    <!-- 标签筛选 -->
    <div class="tags-section">
      <div class="tags-container">
        <span class="tags-label">热门标签：</span>
        <div class="tags-list">
          <el-tag 
            v-for="tag in popularTags" 
            :key="tag.name"
            :type="selectedTags.includes(tag.name) ? 'primary' : ''"
            class="tag-item"
            @click="toggleTag(tag.name)"
          >
            {{ tag.name }} ({{ tag.count }})
          </el-tag>
        </div>
      </div>
    </div>

    <!-- 题目列表 -->
    <div class="problems-section">
      <div class="section-header">
        <h2>编程题目</h2>
        <div class="header-actions">
          <el-button @click="randomProblem">
            <el-icon><Refresh /></el-icon>
            随机一题
          </el-button>
          <el-button type="primary" @click="createProblem">
            <el-icon><Plus /></el-icon>
            创建题目
          </el-button>
        </div>
      </div>

      <div class="problems-table">
        <el-table 
          :data="filteredProblems" 
          style="width: 100%"
          @row-click="viewProblem"
        >
          <el-table-column label="状态" width="80" align="center">
            <template #default="{ row }">
              <el-icon 
                v-if="row.status === 'solved'" 
                class="status-icon solved"
              >
                <CircleCheck />
              </el-icon>
              <el-icon 
                v-else-if="row.status === 'attempted'" 
                class="status-icon attempted"
              >
                <Warning />
              </el-icon>
              <span v-else class="status-icon not-attempted">-</span>
            </template>
          </el-table-column>
          
          <el-table-column label="题目" min-width="300">
            <template #default="{ row }">
              <div class="problem-title">
                <span class="title-text">{{ row.title }}</span>
                <div class="problem-tags">
                  <el-tag 
                    v-for="tag in row.tags.slice(0, 3)" 
                    :key="tag"
                    size="small"
                    class="problem-tag"
                  >
                    {{ tag }}
                  </el-tag>
                  <span v-if="row.tags.length > 3" class="more-tags">
                    +{{ row.tags.length - 3 }}
                  </span>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="难度" width="100" align="center">
            <template #default="{ row }">
              <el-tag 
                :type="getDifficultyType(row.difficulty)"
                size="small"
              >
                {{ getDifficultyText(row.difficulty) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="通过率" width="100" align="center">
            <template #default="{ row }">
              <span :class="getAcceptanceRateClass(row.acceptanceRate)">
                {{ row.acceptanceRate }}%
              </span>
            </template>
          </el-table-column>
          
          <el-table-column label="提交数" width="100" align="center">
            <template #default="{ row }">
              {{ formatNumber(row.submissions) }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="150" align="center">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                size="small"
                @click.stop="solveProblem(row)"
              >
                {{ row.status === 'solved' ? '再次挑战' : '开始解题' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[20, 50, 100]"
          :total="totalProblems"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 每日挑战 -->
    <div class="daily-challenge">
      <div class="challenge-card">
        <div class="challenge-header">
          <h3>每日挑战</h3>
          <el-tag type="warning">{{ getDaysRemaining() }}天后重置</el-tag>
        </div>
        
        <div class="challenge-content">
          <div class="challenge-problem">
            <h4>{{ dailyChallenge.title }}</h4>
            <p>{{ dailyChallenge.description }}</p>
            <div class="challenge-meta">
              <el-tag :type="getDifficultyType(dailyChallenge.difficulty)" size="small">
                {{ getDifficultyText(dailyChallenge.difficulty) }}
              </el-tag>
              <span class="reward">奖励：{{ dailyChallenge.reward }}积分</span>
            </div>
          </div>
          
          <div class="challenge-actions">
            <el-button 
              type="primary" 
              :disabled="dailyChallenge.completed"
              @click="startDailyChallenge"
            >
              {{ dailyChallenge.completed ? '已完成' : '开始挑战' }}
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Monitor, Search, Refresh, Plus, CircleCheck, Warning
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const difficultyFilter = ref('')
const categoryFilter = ref('')
const statusFilter = ref('')
const sortBy = ref('default')
const selectedTags = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const totalProblems = ref(1250)

// 用户统计
const userStats = ref({
  solvedProblems: 45,
  totalSubmissions: 128,
  acceptanceRate: 72
})

// 分类列表
const categories = ref([
  { label: '数组', value: 'array' },
  { label: '字符串', value: 'string' },
  { label: '链表', value: 'linked-list' },
  { label: '树', value: 'tree' },
  { label: '图', value: 'graph' },
  { label: '动态规划', value: 'dp' },
  { label: '贪心算法', value: 'greedy' },
  { label: '回溯', value: 'backtracking' }
])

// 热门标签
const popularTags = ref([
  { name: '数组', count: 245 },
  { name: '哈希表', count: 189 },
  { name: '字符串', count: 156 },
  { name: '动态规划', count: 134 },
  { name: '数学', count: 98 },
  { name: '双指针', count: 87 },
  { name: '排序', value: 76 },
  { name: '栈', count: 65 }
])

// 每日挑战
const dailyChallenge = ref({
  title: '两数之和',
  description: '给定一个整数数组和一个目标值，找出数组中和为目标值的两个数。',
  difficulty: 'easy',
  reward: 50,
  completed: false
})

// 题目列表
const problems = ref([
  {
    id: 1,
    title: '两数之和',
    difficulty: 'easy',
    acceptanceRate: 48.5,
    submissions: 3250000,
    tags: ['数组', '哈希表'],
    status: 'solved',
    category: 'array'
  },
  {
    id: 2,
    title: '无重复字符的最长子串',
    difficulty: 'medium',
    acceptanceRate: 33.2,
    submissions: 2100000,
    tags: ['哈希表', '字符串', '滑动窗口'],
    status: 'attempted',
    category: 'string'
  },
  {
    id: 3,
    title: '寻找两个正序数组的中位数',
    difficulty: 'hard',
    acceptanceRate: 35.8,
    submissions: 1800000,
    tags: ['数组', '二分查找', '分治'],
    status: 'not_attempted',
    category: 'array'
  },
  {
    id: 4,
    title: '最长回文子串',
    difficulty: 'medium',
    acceptanceRate: 31.4,
    submissions: 1950000,
    tags: ['字符串', '动态规划'],
    status: 'not_attempted',
    category: 'string'
  },
  {
    id: 5,
    title: '正则表达式匹配',
    difficulty: 'hard',
    acceptanceRate: 27.9,
    submissions: 890000,
    tags: ['字符串', '动态规划', '回溯'],
    status: 'not_attempted',
    category: 'string'
  }
  // 更多题目数据...
])

// 计算属性
const filteredProblems = computed(() => {
  let filtered = problems.value

  // 难度筛选
  if (difficultyFilter.value) {
    filtered = filtered.filter(p => p.difficulty === difficultyFilter.value)
  }

  // 分类筛选
  if (categoryFilter.value) {
    filtered = filtered.filter(p => p.category === categoryFilter.value)
  }

  // 状态筛选
  if (statusFilter.value) {
    filtered = filtered.filter(p => p.status === statusFilter.value)
  }

  // 标签筛选
  if (selectedTags.value.length > 0) {
    filtered = filtered.filter(p => 
      selectedTags.value.some(tag => p.tags.includes(tag))
    )
  }

  // 搜索筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(p => 
      p.title.toLowerCase().includes(keyword) ||
      p.tags.some(tag => tag.toLowerCase().includes(keyword))
    )
  }

  // 排序
  switch (sortBy.value) {
    case 'difficulty_asc':
      filtered.sort((a, b) => {
        const order = { easy: 1, medium: 2, hard: 3 }
        return order[a.difficulty] - order[b.difficulty]
      })
      break
    case 'difficulty_desc':
      filtered.sort((a, b) => {
        const order = { easy: 1, medium: 2, hard: 3 }
        return order[b.difficulty] - order[a.difficulty]
      })
      break
    case 'acceptance_rate':
      filtered.sort((a, b) => b.acceptanceRate - a.acceptanceRate)
      break
    case 'latest':
      filtered.sort((a, b) => b.id - a.id)
      break
    default:
      // 默认排序
      break
  }

  return filtered
})

// 方法
const getDifficultyType = (difficulty) => {
  const typeMap = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  }
  return typeMap[difficulty] || ''
}

const getDifficultyText = (difficulty) => {
  const textMap = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return textMap[difficulty] || difficulty
}

const getAcceptanceRateClass = (rate) => {
  if (rate >= 50) return 'rate-high'
  if (rate >= 30) return 'rate-medium'
  return 'rate-low'
}

const formatNumber = (num) => {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M'
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K'
  }
  return num.toString()
}

const getDaysRemaining = () => {
  // 计算距离下次重置的天数
  const now = new Date()
  const tomorrow = new Date(now)
  tomorrow.setDate(tomorrow.getDate() + 1)
  tomorrow.setHours(0, 0, 0, 0)
  
  const diff = tomorrow - now
  return Math.ceil(diff / (1000 * 60 * 60 * 24))
}

const toggleTag = (tagName) => {
  const index = selectedTags.value.indexOf(tagName)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  } else {
    selectedTags.value.push(tagName)
  }
  currentPage.value = 1
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const viewProblem = (problem) => {
  router.push(`/coding/problem/${problem.id}`)
}

const solveProblem = (problem) => {
  router.push(`/coding/solve/${problem.id}`)
}

const randomProblem = () => {
  const randomIndex = Math.floor(Math.random() * problems.value.length)
  const problem = problems.value[randomIndex]
  solveProblem(problem)
}

const createProblem = () => {
  router.push('/coding/create')
}

const startDailyChallenge = () => {
  router.push('/coding/daily-challenge')
}

onMounted(() => {
  // 初始化数据
})
</script>

<style lang="scss" scoped>
.coding-container {
  min-height: 100vh;
  background: var(--el-bg-color-page);
}

.coding-header {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  padding: 60px 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 60px;
  align-items: center;
  
  @media (max-width: 768px) {
    grid-template-columns: 1fr;
    gap: 30px;
  }
}

.header-left {
  h1 {
    font-size: 3rem;
    font-weight: 700;
    margin-bottom: 16px;
  }
  
  p {
    font-size: 1.25rem;
    opacity: 0.9;
    margin-bottom: 32px;
  }
}

.quick-stats {
  display: flex;
  gap: 40px;
  
  @media (max-width: 768px) {
    gap: 20px;
  }
}

.stat-item {
  text-align: center;
  
  .number {
    display: block;
    font-size: 2rem;
    font-weight: 700;
    margin-bottom: 4px;
  }
  
  .label {
    font-size: 0.9rem;
    opacity: 0.8;
  }
}

.header-right {
  display: flex;
  justify-content: center;
}

.coding-illustration {
  position: relative;
  width: 200px;
  height: 150px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10px);
  
  .code-icon {
    font-size: 48px;
    margin-bottom: 20px;
  }
  
  .code-lines {
    position: absolute;
    bottom: 20px;
    left: 20px;
    right: 20px;
    
    .code-line {
      height: 3px;
      background: rgba(255, 255, 255, 0.6);
      margin-bottom: 6px;
      border-radius: 2px;
      
      &.short {
        width: 60%;
      }
      
      &.medium {
        width: 80%;
      }
    }
  }
}

.filter-section {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

.filter-content {
  display: flex;
  gap: 20px;
  align-items: center;
  
  @media (max-width: 768px) {
    flex-direction: column;
    align-items: stretch;
  }
}

.search-bar {
  flex: 1;
  max-width: 400px;
}

.filter-controls {
  display: flex;
  gap: 12px;
  
  @media (max-width: 768px) {
    flex-wrap: wrap;
  }
}

.tags-section {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px 30px;
}

.tags-container {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
  
  .tags-label {
    font-weight: 500;
    color: var(--el-text-color-primary);
    white-space: nowrap;
  }
}

.tags-list {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.tag-item {
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-1px);
  }
}

.problems-section {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px 40px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  
  h2 {
    font-size: 1.5rem;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
  
  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.problems-table {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  margin-bottom: 24px;
  
  :deep(.el-table) {
    .el-table__row {
      cursor: pointer;
      
      &:hover {
        background: var(--el-fill-color-extra-light);
      }
    }
  }
}

.status-icon {
  &.solved {
    color: var(--el-color-success);
    font-size: 18px;
  }
  
  &.attempted {
    color: var(--el-color-warning);
    font-size: 18px;
  }
  
  &.not-attempted {
    color: var(--el-text-color-placeholder);
    font-size: 16px;
  }
}

.problem-title {
  .title-text {
    font-weight: 500;
    color: var(--el-text-color-primary);
    margin-bottom: 4px;
    display: block;
  }
  
  .problem-tags {
    display: flex;
    gap: 4px;
    align-items: center;
    flex-wrap: wrap;
  }
  
  .problem-tag {
    font-size: 11px;
  }
  
  .more-tags {
    font-size: 12px;
    color: var(--el-text-color-placeholder);
  }
}

.rate-high {
  color: var(--el-color-success);
  font-weight: 500;
}

.rate-medium {
  color: var(--el-color-warning);
  font-weight: 500;
}

.rate-low {
  color: var(--el-color-danger);
  font-weight: 500;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.daily-challenge {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px 40px;
}

.challenge-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  border-left: 4px solid var(--el-color-primary);
}

.challenge-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  
  h3 {
    font-size: 18px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.challenge-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 24px;
  
  @media (max-width: 768px) {
    flex-direction: column;
  }
}

.challenge-problem {
  flex: 1;
  
  h4 {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 8px;
    color: var(--el-text-color-primary);
  }
  
  p {
    font-size: 14px;
    color: var(--el-text-color-secondary);
    margin-bottom: 12px;
    line-height: 1.5;
  }
}

.challenge-meta {
  display: flex;
  gap: 16px;
  align-items: center;
  
  .reward {
    font-size: 14px;
    color: var(--el-color-primary);
    font-weight: 500;
  }
}

.challenge-actions {
  flex-shrink: 0;
}
</style>
